package com.linchong.set;

import java.util.HashMap;
import java.util.Map;


/**
 * @author linchong
 * @version 1.0
 * @Date: 2020-12-05 14:27
 * @Description: ValidAnagram$
 * 给定两个字符串 s 和 t ，编写一个函数来判断 t 是否是 s 的字母异位词。
 *
 * 示例 1:
 *
 * 输入: s = "anagram", t = "nagaram"
 * 输出: true
 * 示例 2:
 *
 * 输入: s = "rat", t = "car"
 * 输出: false
 * 说明:
 * 你可以假设字符串只包含小写字母。
 *
 * 来源：力扣（LeetCode）
 * 链接：https://leetcode-cn.com/problems/valid-anagram
 *
 */
public class ValidAnagram {

	public boolean isAnagram(String s, String t) {
		if(t.length()!=s.length()){
			return false;
		}

		int[] res = new int[26];
		for(int i = 0; i< s.length(); i++) {
			res[s.charAt(i) - 'a'] ++;
			res[t.charAt(i) - 'a'] --;
		}
		for(int i=0;i<26;i++) {
			if (res[i] != 0) {
				return false;
			}
		}
		return true;
	}
	public boolean isAnagram2(String s, String t) {
		int lent = t.length();
		int lens = s.length();
		if(lens!=lent){
			return false;
		}

		Map<Character,Integer> maps = new HashMap<>(2);
		Map<Character,Integer> mapt = new HashMap<>(2);
		char[] chars = s.toCharArray();
		char[] chart = t.toCharArray();
		for (char ch : chars) {
			if(!maps.containsKey(ch)){
				maps.put(ch,1);
			}else{
				Integer count = maps.get(ch);
				maps.put(ch,++count);
			}
		}

		for (char ch : chart) {
			if(!mapt.containsKey(ch)){
				mapt.put(ch,1);
			}else{
				Integer count = mapt.get(ch);
				mapt.put(ch,++count);
			}
		}

		for (Character character : maps.keySet()) {
			if(!maps.get(character).equals(mapt.get(character))){
				return false;
			}
		}
		return true;
	}

	public static void main(String[] args) {
		String s = "aacc";
		String t = "acaa";
		ValidAnagram instance = new ValidAnagram();
		System.out.println(instance.isAnagram(s,t));
	}
}
